<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader v-model="selectedKeys" :options="cateoptions" :props="cascaderProps" @change="handleChange" clearable></el-cascader>
        </el-col>
      </el-row>
      <!-- 选项卡 -->
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="iaBurronDisable" @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="ParamsForm" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="removeParams(i, scope.row)">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput()">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="320px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="iaBurronDisable" @click="addDialogVisible=true">添加属性</el-button>
           <el-table :data="ParamsForm" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="removeParams(i, scope.row)">{{item}}</el-tag>
                <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput()">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作" width="320px">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRole(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数 -->
    <el-dialog title="添加参数" :visible.sync="addDialogVisible" width="50%" @close="addFormClosed">
      <el-form label-width="70px" :model="addForm"  ref="addFormref" :rules="addrules">
        <!-- 用户输入框 -->
        <el-form-item :label="tilteTxt" prop="attr_name" label-width="80px">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
     <!-- 编辑参数 -->
    <el-dialog title="编辑参数" :visible.sync="editDialogVisible" width="50%" @close="editFormClosed">
      <el-form label-width="70px" :model="editForm"  ref="editFormref" :rules="addrules">
        <!-- 用户输入框 -->
        <el-form-item :label="tilteTxt" prop="attr_name" label-width="80px">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      selectedKeys: [],
      cateoptions: [],
      cascaderProps: {
        label: 'cat_name',
        children: 'children',
        value: 'cat_id',
        expandTrigger: 'hover'
      },
      activeName: 'many',
      ParamsForm: [],
      addForm: {
        attr_name: ''
      },
      editForm: {
        attr_name: '',
        attr_id: ''
      },
      addDialogVisible: false,
      addrules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      inputVisible: false,
      inputValue: ''
    }
  },
  created () {
    this.getCate()
  },
  methods: {
    handleChange () {
      if (this.selectedKeys.length !== 3) return
      this.getParamList()
    },
    async getCate () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.cateoptions = res.data
    },
    handleClick () {
      this.getParamList()
    },
    async getParamList () {
      const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`, { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      this.ParamsForm = res.data
    },
    addFormClosed () {
      this.$refs.addFormref.resetFields()
    },
    editFormClosed () {
      this.$refs.editFormref.resetFields()
    },
    showEditDialog (id) {
      this.editDialogVisible = true
      this.editForm.attr_id = id
    },
    async removeRole (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${id}`
      )
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      this.getParamList()
    },
    async addParams () {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 201) return this.$message.error('添加参数失败')
      this.$message.success('添加参数成功')
      this.addDialogVisible = false
      this.getParamList()
    },
    async editParams () {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name, attr_sel: this.activeName
        }
      )
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
      this.editDialogVisible = false
      this.getParamList()
    },
    handleInputConfirm (row) {
      if (this.inputValue.trim() === '') {
        this.inputVisible = false
        this.inputValue = ''
        return
      }
      row.attr_vals.push(this.inputValue)
      this.saveAttrVals(row)
    },
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
      this.inputVisible = false
      this.inputValue = ''
    },
    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    removeParams (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    iaBurronDisable () {
      if (this.selectedKeys.length === 3) {
        return false
      }
      return true
    },
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2]
      }
      return null
    },
    tilteTxt () {
      if (this.activeName === 'many') return '动态参数'
      return '静态属性'
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin: 10px 0;
}
.el-tag {
  margin-right: 5px;
}
.input-new-tag {
  width: 80px;
}
</style>
